package com.gylang.pdf;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.util.Locale;

/**
 * freemarker 模板渲染
 * @author gylang
 * data 2022/1/13
 */
public abstract class AbstractFreemarkerTemplateProcessor implements ITemplateProcessor {

    protected Configuration configuration;
    protected StringTemplateLoader stringTemplateLoader;

    /**
     * 初始化加载配置
     */
    public abstract void init();

    public Template getTemplate(String name) throws IOException {
        return configuration.getTemplate(name);
    }

    public Template getTemplate(String name, Locale locale) throws IOException {
        return configuration.getTemplate(name, locale);
    }

    public Template getTemplate(String name, Locale locale, String encode) throws IOException {
        return configuration.getTemplate(name, locale, encode);
    }

    public Template getTemplate(String name, Locale locale, String encode, boolean parseAsFTL) throws IOException {
        return configuration.getTemplate(name, locale, encode, parseAsFTL);
    }

    public Template getTemplate(String name, Locale locale, String encode, boolean parseAsFTL, boolean ignoreMissing) throws IOException {
        return configuration.getTemplate(name, locale, encode, parseAsFTL, ignoreMissing);
    }

    public Template createTemplate(String name, String source) throws IOException {
        return new Template(name, source, configuration);
    }

    public Template createTemplate(String name, Reader reader, String encode) throws IOException {
        return new Template(name, reader, configuration, encode);
    }

    public Template pushTemplate(String name, String source) throws IOException {
        Template template = createTemplate(name, source);
        stringTemplateLoader.putTemplate(name, source);
        return template;
    }


    public boolean removeTemplate(String name) {
        return stringTemplateLoader.removeTemplate(name);
    }

    public String render(String name, Object obj) throws IOException, TemplateException {
        StringWriter out = new StringWriter();
        configuration.getTemplate(name).process(obj, out);
        return out.toString();
    }


    public String render(String name, String templateSource, Object obj) throws IOException, TemplateException {
        StringWriter out = new StringWriter();
        createTemplate(name, templateSource).process(obj, out);
        return out.toString();
    }
}
